﻿using System.Collections.Generic;
using System.Web.Mvc;
using Company.Infrastructure;
using Company.Model;
using Company.Model.Services;
using Company.Services;
using Company.Web.Infrastructure;
using Company.Web.Model;

namespace Company.Web.Controllers
{
    public class AccountController : Controller
    {
        
        private ILoginsViewTask m_LoginsViewTask = new LoginsViewTask();
        private IUsersService m_UsersService = new UsersService();
        private ISessionService m_SessionService = new SessionService();

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult IndexLogin()
        {
            return View("Login", m_LoginsViewTask.DefaultView());
        }

        [HttpPost]
        public ActionResult Login(LoginsView view)
        {
            if (ModelState.IsValid)
            {
                IUsers m_users = m_UsersService.GetUser(view.UserName, view.Password);
                if (m_users != null)
                {
                    m_SessionService.SigIn(m_users);
                    return RedirectToAction("Index", "Home", new {CompanyName = m_users.EmpresaModel.Nombre});
                }
                Errors(m_UsersService.GetRuleViolations());
            }
            return View("Login",view);
        }

        public ActionResult NewAccount()
        {
            return View("NewAccount", m_LoginsViewTask.DefaultAccountView());
        }

        public ActionResult SignOut()
        {
            m_SessionService.SignOut();
            return RedirectToAction("Index");
        }

        private void Errors(List<RuleViolations> rules)
        {
            foreach (var m_list in rules)
            {
                ModelState.AddModelError(m_list.PropertyName,m_list.ErrorMessage);
            }
        }
    }
}
